//
//  WelcomeViewController.swift
//  WeiBo_One
//
//  Created by 李炎 on 15/10/25.
//  Copyright © 2015年 蜡笔小炎. All rights reserved.
//

import UIKit
import SDWebImage

class WelcomeViewController: UIViewController {
    // 懒加载子控件
    lazy var iconImageView: UIImageView = {
    
        var view = UIImageView(imageName: "avatar_default_big")
    
        view.layer.cornerRadius = 45
        view.layer.masksToBounds = true
        return view
    }()
    
    lazy var backgroundImageView: UIImageView = UIImageView(imageName: "ad_background")
    lazy var welcomeLabel: UILabel = UILabel(title: "欢迎归来", fontSize: 16)
    
    override func loadView() {
        super.loadView()
        
        //替换根视图
        view = backgroundImageView
        //设置子控件
        setupUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置头像图片
        let iconURL = NSURL(string: UserAccountViewModel.sharedAccoutViewModel.account?.avatar_large ?? "")
        iconImageView.sd_setImageWithURL(iconURL!, placeholderImage: UIImage(named: "avatar_default_big"))
    }
    
    // 设置控件
    func setupUI() {
        
        view.addSubview(iconImageView)
        view.addSubview(welcomeLabel)
        
        welcomeLabel.alpha = 0.0
        
         //自动布局
        iconImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(view.snp_centerX)
            make.top.equalTo(view.snp_top).offset(300)
            make.width.equalTo(90)
            make.height.equalTo(90)
        }
        welcomeLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(backgroundImageView.snp_centerX)
            make.top.equalTo(iconImageView.snp_bottom).offset(20)
        }
    }
    
    // 控制器根视图显示
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        iconImageView.snp_updateConstraints { (make) -> Void in
            make.top.equalTo(view.snp_top).offset(100)
        }
        
        UIView.animateWithDuration(1.2,
            delay: 0,
            usingSpringWithDamping: 0.6,
            initialSpringVelocity: 1,
            options: [],
            animations: { () -> Void in
                self.view.layoutIfNeeded()
            }) { _ in
                self.welcomeLabel.alpha = 1.0
                
                // 延时执行
                delay(0.5, callFunc: { () -> () in
                
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootControllerNotification, object: nil)
                })
        }
        
    }
}
